<template>
    <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
        <el-steps :active="active">
            <template v-for="(step, index) in steps" :key="index">
                <el-step>
                    <template #title>
                        <span class="step-title" @click="active = step.value">{{ step.title }}</span>
                    </template>
                </el-step>
            </template>
        </el-steps>

        <div v-show="active === 1" class="step1">
            <el-form-item label="节点名称">
                <el-input v-model="form.nodeName"></el-input>
            </el-form-item>
            <el-form-item label="节点ID">
                <el-input v-model="form.typeConcatName" disabled></el-input>
            </el-form-item>
            <el-form-item label="数据所在节点">
                <el-select v-model="form.node" @change="nodeChange">
                    <el-option
                        v-for="item in nodeList"
                        :key="item.id"
                        :label="`${item.nodeName} (${item.name})`"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="目标字段">
              <el-input v-model="form.ConcatFields.targetFieldName"></el-input>
            </el-form-item>
            <el-form-item label="目标字段长度">
              <el-input v-model="form.ConcatFields.targetFieldLength"></el-input>
            </el-form-item>
            <el-form-item label="分隔符">
              <el-input v-model="form.separator"></el-input>
            </el-form-item>
            <el-form-item label="包围字符">
              <el-input v-model="form.enclosure"></el-input>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 2">下一步</el-button>
            </dialog-footer>

        </div>
        <div v-show="active === 2" class="step2">
            <div style="margin-bottom: 10px;">
                <el-button
                    type="primary"
                    size="small"
                    @click="addField"
                >新增字段</el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="batchDelete"
                    :disabled="selectedRows.length === 0"
                >删除选中</el-button>

            </div>
            <el-table :data="form.fields.field" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="30"/>
                <el-table-column label="序号" width="50" header-align="center" align="center">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="字段" width="150">
                  <template #default="scope">
                    <el-select v-model="scope.row.name">
                      <el-option
                          v-for="item in form.fieldList"
                          :key="item.name"
                          :label="item.name"
                          :value="item.name">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="150">
                  <template #default="scope">
                    <el-select v-model="scope.row.type">
                      <el-option
                          v-for="item in typeList"
                          :key="item.dictLabel"
                          :label="item.dictLabel"
                          :value="item.dictLabel"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="format" label="格式" width="150">
                  <template #default="scope">
                    <el-select v-model="scope.row.format">
                      <el-option
                          v-for="item in formatList"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictValue"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="nullif" label="等值判空" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.nullif"/>
                  </template>
                </el-table-column>
                <el-table-column prop="trimtype" label="去除空格" width="150">
                  <template #default="scope">
                    <el-select v-model="scope.row.trim_type">
                      <el-option
                          v-for="item in trimspacesList"
                          :key="item"
                          :label="item"
                          :value="item"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button
                            type="danger"
                            size="small"
                            @click="deleteField(scope.$index)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 1">上一步</el-button>
            </dialog-footer>
        </div>
    </el-form>
</template>

<script setup>
import {defineComponent, ref, onMounted, reactive, watch, computed} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import { getDicts } from '@base/api/base/dict/data'

const flowCount = flowServiceStore();
import {storeToRefs} from 'pinia';

const {flowData} = storeToRefs(flowCount);
import {search as datasourceList} from '@data/api/data/datasource'
import { selectTables, selectSchema, selectColumns, selectTableInfo, selectColumnsByQuerySql } from '@data/api/data/datacollection'

import {cloneDeep} from "lodash-es";
import {ElMessage} from "element-plus";

defineComponent({
    name: 'ConcatFields',
});
const props = defineProps({
    detailObject: {
        type: Object,
        default: () => {
        },
    },
})
const nodeList = computed(() => {
    return Object.entries(flowData.value)
        .filter(([nodeId]) => nodeId !== props.detailObject.id)
        .map(([id, node]) => ({
            id,
            ...node
        }))
})
console.log(nodeList.value)
const steps = ref([
    { value: 1, title: '基础属性' },
    { value: 2, title: '字段拆分' }
]);
const active = ref(1);

const loading = ref(false);

const form = reactive({
    nodeName: '',
    name: '',
    type: 'ConcatFields',
    distribute: 'Y',
    copies: 1,
    partitioning: {
      method: 'none',
      schema_name: ''
    },
    ConcatFields: {
      targetFieldName: '',
      targetFieldLength: '',
      removeSelectedFields: 'N'
    },
    separator: '',
    enclosure: '',

    node: '',
    description: '',

    fieldList: [],
    fields: {
        field: []
    },

    custom_distribution: '',
    GUI: {
        xloc: 1,
        yloc: 1,
        draw: 'Y'
    }
});

const emit = defineEmits(['cancel']);

onMounted(async () => {
    getTypeList();
    getFormatList();
    form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
    form.node = flowData.value[props.detailObject.id]?.node || '';
    form.fields.field = flowData.value[props.detailObject.id]?.fields?.field || [];
    form.description = flowData.value[props.detailObject.id]?.description || '';
    form.separator = flowData.value[props.detailObject.id]?.separator || '';
    form.enclosure = flowData.value[props.detailObject.id]?.enclosure || '';
    form.ConcatFields.targetFieldName = flowData.value[props.detailObject.id]?.ConcatFields.targetFieldName || '';
    form.ConcatFields.targetFieldLength = flowData.value[props.detailObject.id]?.ConcatFields.targetFieldLength || '';
    form.ConcatFields.removeSelectedFields = flowData.value[props.detailObject.id]?.ConcatFields.removeSelectedFields || 'N'

    if(form.node){
        nodeChange(form.node);
    } else {
        form.fields.field = [
            {
              name: '',
              type: '',
              format: '',
              nullif: '',
              trim_type: ''
            }
        ]
    }

    form.name = props.detailObject.id;
    form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;


})
const typeList = ref([]);
const getTypeList= () => {
  getDicts('ktr_field_type').then((response) => {
    typeList.value = response.data
  })
};

const formatList = ref([]);
const getFormatList= () => {
  getDicts('date_format').then((response) => {
    formatList.value = response.data
  })
};
const trimspacesList = ref(['none','left','right','both']);

const nodeChange = (value) => {
    nodeList.value.forEach((item) => {
        if (item.id === value && item.fields?.field) {
            form.fieldList = cloneDeep(item.fieldList);
        }
    })
}

const selectedRows = ref([])
// 处理选择变化
const handleSelectionChange = (val) => {
    selectedRows.value = val
}
// 批量删除方法
const batchDelete = () => {
    if (selectedRows.value.length === 0) return
    const indexes = selectedRows.value.map(row =>
        form.fields.field.indexOf(row)
    ).sort((a,b) => b - a)
    indexes.forEach(index => {
        form.fields.field.splice(index, 1)
    })
    selectedRows.value = []
}
const addField = () => {
    form.fields.field.push({
      name: '',
      type: '',
      format: '',
      nullif: '',
      trim_type: ''
    });
}
const deleteField = (index) => {
    form.fields.field.splice(index, 1);
}

const submitForm = () => {
    const obj = {
                  name:form.ConcatFields.targetFieldName,
                  type:"String"
                }
    form.fieldList.push(obj);
    flowCount.setFlowData({
        ...flowData.value,
        [props.detailObject.id]: {
            ...form,
            name: `${form.type}-${form.name}`,
        }
    })
    console.log(flowData.value);
    emit('cancel');
}
const cancel = () => {
    emit('cancel');
}
</script>

<style scoped>

</style>